package com.jiai.live.im.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.socket.ChannelInputShutdownEvent;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginOutHandler extends ChannelHandlerAdapter {
	private Logger logger= LoggerFactory.getLogger(LoginOutHandler.class);
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelActive(ctx);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		 try {
		        Channel channel = ctx.channel();
		        if (evt instanceof IdleStateEvent) {
		            IdleStateEvent e = (IdleStateEvent) evt;
		            if (e.state() == IdleState.READER_IDLE) {
		                channel.close();  //call back channelInactive(ChannelHandlerContext ctx)
		                if (logger.isDebugEnabled()) logger
		                        .debug(channel.remoteAddress() + "---No data was received for a while ,read time out... ...");
		            } //     because we are attaching  more importance to the read_idle time(timeout to rec)
		            else if (e.state() == IdleState.WRITER_IDLE) { // No data was sent for a while.
		                channel.close();
		                if (logger.isDebugEnabled()) logger
		                        .debug(channel.remoteAddress() + "---No data was sent for a while.write time out... ...");
		            }
		        } else if (evt instanceof ChannelInputShutdownEvent) {
		            channel.close();//远程主机强制关闭连接
		        }
		    } catch (Exception e) {
		        e.printStackTrace();
		    }
	}

	@Override
	public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise)
			throws Exception {
		// TODO Auto-generated method stub
		super.disconnect(ctx, promise);
		
	}
	
	

}
